package org.lifxue.jqda.ui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Timer;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;

import org.lifxue.jqda.App;
import org.lifxue.jqda.data.DataUtil;
import org.lifxue.jqda.run.IndexTask;
import org.lifxue.jqda.util.GlobalVar;

/**
 * 
 * @Description:
 * @Author: zhangzuoqiang
 * @Date: Sep 26, 2011
 */
public class IndexerSettingJDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// private static Log logger =
	// LogFactory.getLog(QuickStartSettingJDialog.class);

	private List<String> IS_DIR;// 扫描目录
	private List<String> IS_INDEX_TYPE;// 搜索文件类型
	private String IS_INDEX_CYCLE;// 搜索周期
	private static IndexerSettingJDialog IS_JDIALOG;

	public static IndexerSettingJDialog getInstance(boolean modal) {
		synchronized (IndexerSettingJDialog.class) {
			if (IS_JDIALOG == null) {
				IS_JDIALOG = new IndexerSettingJDialog(modal);
			}
		}
		return IS_JDIALOG;
	}

	public IndexerSettingJDialog(boolean modal) {
		super(new JFrame(), modal);
		init();

		initComponents();

		// 窗口定位
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = getSize();
		setLocation(new Point((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.width) / 2));

	}

	/** Creates new form IndexerSettingJDialog */
	public IndexerSettingJDialog(Frame parent, boolean modal) {
		super(parent, modal);
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">
	private void initComponents() {

		jScrollPane1 = new JScrollPane();
		DefaultListModel listModel = new DefaultListModel();
		// listModel.addElement("C:\\Program Files");
		for (String dir : IS_DIR) {
			listModel.addElement(dir);
		}
		dirjList = new JList();
		addjButton = new JButton();
		deductjButton = new JButton();
		txtjToggleButton = new JToggleButton();
		jLabel1 = new JLabel();
		pdfjToggleButton = new JToggleButton();
		docjToggleButton = new JToggleButton();
		xlsjToggleButton = new JToggleButton();
		cyclejComboBox = new JComboBox();
		jSeparator1 = new JSeparator();
		okjButton = new JButton();
		canclejButton = new JButton();

		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		setTitle("索引设置");

		jScrollPane1.setBorder(BorderFactory.createTitledBorder("目录"));

		dirjList.setModel(listModel);
		jScrollPane1.setViewportView(dirjList);

		addjButton.setText("+");
		addjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				addjButtonActionPerformed(evt);
			}
		});

		deductjButton.setText("-");
		deductjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				deductjButtonActionPerformed(evt);
			}
		});

		txtjToggleButton.setText("文本");
		txtjToggleButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				txtjToggleButtonActionPerformed(evt);
			}
		});
		if (this.IS_INDEX_TYPE.contains("txt")) {
			txtjToggleButton.setSelected(true);
		}

		jLabel1.setText("文件类型：");

		pdfjToggleButton.setText("PDF");
		pdfjToggleButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				pdfjToggleButtonActionPerformed(evt);
			}
		});
		if (this.IS_INDEX_TYPE.contains("pdf")) {
			pdfjToggleButton.setSelected(true);
		}

		docjToggleButton.setText("DOC");
		docjToggleButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				docjToggleButtonActionPerformed(evt);
			}
		});
		if (this.IS_INDEX_TYPE.contains("doc")) {
			docjToggleButton.setSelected(true);
		}

		xlsjToggleButton.setText("XLS");
		xlsjToggleButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				xlsjToggleButtonActionPerformed(evt);
			}
		});
		if (this.IS_INDEX_TYPE.contains("xls")) {
			xlsjToggleButton.setSelected(true);
		}

		cyclejComboBox.setModel(new DefaultComboBoxModel(new String[] { "每天一次",
				"每周一次", "每旬一次", "每月一次", "每季一次" }));
		cyclejComboBox.setSelectedItem(this.IS_INDEX_CYCLE);
		cyclejComboBox.setBorder(BorderFactory.createTitledBorder(null, "索引周期",
				TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.ABOVE_TOP,
				new Font("微软雅黑", 3, 12)));
		cyclejComboBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent evt) {
				cyclejComboBoxItemStateChanged(evt);
			}
		});

		okjButton.setText("确定");
		okjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				okjButtonActionPerformed(evt);
			}
		});

		canclejButton.setText("取消");
		canclejButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				canclejButtonActionPerformed(evt);
			}
		});

		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.LEADING)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addContainerGap()
																								.addComponent(
																										jScrollPane1,
																										GroupLayout.PREFERRED_SIZE,
																										405,
																										GroupLayout.PREFERRED_SIZE))
																				.addGroup(
																						layout.createSequentialGroup()
																								.addGap(98,
																										98,
																										98)
																								.addComponent(
																										addjButton,
																										GroupLayout.PREFERRED_SIZE,
																										78,
																										GroupLayout.PREFERRED_SIZE)
																								.addGap(70,
																										70,
																										70)
																								.addComponent(
																										deductjButton,
																										GroupLayout.PREFERRED_SIZE,
																										80,
																										GroupLayout.PREFERRED_SIZE)))
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.UNRELATED)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.LEADING)
																				.addComponent(
																						cyclejComboBox,
																						0,
																						116,
																						Short.MAX_VALUE)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										docjToggleButton)
																								.addPreferredGap(
																										LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										xlsjToggleButton))
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										txtjToggleButton)
																								.addPreferredGap(
																										LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										pdfjToggleButton))
																				.addComponent(
																						jLabel1)))
												.addGroup(
														layout.createSequentialGroup()
																.addContainerGap()
																.addComponent(
																		jSeparator1,
																		GroupLayout.DEFAULT_SIZE,
																		533,
																		Short.MAX_VALUE)))
								.addContainerGap())
				.addGroup(
						GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap(398, Short.MAX_VALUE)
								.addComponent(okjButton)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(canclejButton).addGap(37, 37, 37)));

		layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {
				addjButton, deductjButton });

		layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {
				docjToggleButton, pdfjToggleButton, txtjToggleButton,
				xlsjToggleButton });

		layout.setVerticalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		jLabel1)
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.BASELINE)
																				.addComponent(
																						txtjToggleButton)
																				.addComponent(
																						pdfjToggleButton))
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.BASELINE)
																				.addComponent(
																						docjToggleButton)
																				.addComponent(
																						xlsjToggleButton))
																.addGap(52, 52,
																		52)
																.addComponent(
																		cyclejComboBox,
																		GroupLayout.PREFERRED_SIZE,
																		64,
																		GroupLayout.PREFERRED_SIZE))
												.addComponent(
														jScrollPane1,
														GroupLayout.PREFERRED_SIZE,
														219,
														GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.BASELINE)
												.addComponent(deductjButton)
												.addComponent(addjButton))
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED,
										12, Short.MAX_VALUE)
								.addComponent(jSeparator1,
										GroupLayout.PREFERRED_SIZE, 10,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.BASELINE)
												.addComponent(okjButton)
												.addComponent(canclejButton))
								.addContainerGap(12, Short.MAX_VALUE)));

		pack();
	}

	private void addjButtonActionPerformed(ActionEvent evt) {
		// 建立文件选择框对象
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		// 设定文件选择框标题
		fc.setDialogTitle("选择目录");
		// 显示文件选择框，在选择后将结果储存到returnVal变量中
		int returnVal = fc.showSaveDialog(this);
		// 如果用户选择了文件，并点击了"Opne/打开"按钮，显示用户选择的文件全名路径，
		// 如果用户点击"Close/关闭"按钮，以及其它方式退出文件选择框，则什么也不做。
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			if (file == null) {
				return;
			}
			DefaultListModel listModel = (DefaultListModel) dirjList.getModel();
			for (int i = 0; i < listModel.getSize(); i++) {
				String temp = (String) listModel.get(i);
				if (temp.equals(file.getPath())) {// 如果重复目录，跳过，不保存
					dirjList.setSelectedIndex(i);
					return;
				}
			}
			listModel.addElement(file.getPath());
			IS_DIR.add(file.getPath());
			dirjList.setSelectedIndex(listModel.getSize() - 1);
		}
	}

	private void deductjButtonActionPerformed(ActionEvent evt) {
		DefaultListModel model = (DefaultListModel) dirjList.getModel();
		int[] indexs = dirjList.getSelectedIndices();
		Object[] obj = dirjList.getSelectedValues();
		for (int i = indexs.length - 1; i >= 0; i--) {
			model.remove(indexs[i]);
			IS_DIR.remove(obj[i].toString());
		}
	}

	private void canclejButtonActionPerformed(ActionEvent evt) {
		this.setVisible(false);
		this.dispose();
		IS_JDIALOG = null;
	}

	private void okjButtonActionPerformed(ActionEvent evt) {
		GlobalVar.INDEX_SCAN_DIR = this.IS_DIR;
		GlobalVar.INDEX_SCAN_TYPE = this.IS_INDEX_TYPE;
		GlobalVar.INDEX_CYCLE = this.IS_INDEX_CYCLE;

		App.APP_Timer.cancel();
		App.APP_Timer = new Timer();
		IndexTask indexTask = new IndexTask(GlobalVar.INDEX_SCAN_DIR,
				GlobalVar.INDEX_SCAN_TYPE);
		long period = 0;
		if (GlobalVar.INDEX_CYCLE.equals("每天一次")) {
			period = 24 * 60 * 60 * 1000;
		} else if (GlobalVar.INDEX_CYCLE.equals("每周一次")) {
			period = 7 * 24 * 60 * 60 * 1000;
		} else if (GlobalVar.INDEX_CYCLE.equals("每旬一次")) {
			period = 10 * 24 * 60 * 60 * 1000;
		} else if (GlobalVar.INDEX_CYCLE.equals("每月一次")) {
			period = 30 * 24 * 60 * 60 * 1000;
		} else if (GlobalVar.INDEX_CYCLE.equals("每季一次")) {
			period = 3 * 30 * 24 * 60 * 60 * 1000;
		}
		App.APP_Timer.schedule(indexTask, 0, period);

		Date date = new Date();
		GlobalVar.INDEX_LASTTIME = String.valueOf(date.getTime());// 当前时间（毫秒）

		DataUtil.updateIndexFile();// 保存数据到文件

		canclejButtonActionPerformed(evt);
	}

	private void txtjToggleButtonActionPerformed(ActionEvent evt) {
		if (txtjToggleButton.isSelected()) {// 选定
			if (!IS_INDEX_TYPE.contains("txt")) {
				IS_INDEX_TYPE.add("txt");
			}
		} else {
			if (IS_INDEX_TYPE.contains("txt")) {
				IS_INDEX_TYPE.remove("txt");
			}
		}
	}

	private void pdfjToggleButtonActionPerformed(ActionEvent evt) {
		if (pdfjToggleButton.isSelected()) {// 选定
			if (!IS_INDEX_TYPE.contains("pdf")) {
				IS_INDEX_TYPE.add("pdf");
			}
		} else {
			if (IS_INDEX_TYPE.contains("pdf")) {
				IS_INDEX_TYPE.remove("pdf");
			}
		}
	}

	private void docjToggleButtonActionPerformed(ActionEvent evt) {
		if (docjToggleButton.isSelected()) {// 选定
			if (!IS_INDEX_TYPE.contains("doc")) {
				IS_INDEX_TYPE.add("doc");
			}
		} else {
			if (IS_INDEX_TYPE.contains("doc")) {
				IS_INDEX_TYPE.remove("doc");
			}
		}
	}

	private void xlsjToggleButtonActionPerformed(ActionEvent evt) {
		if (xlsjToggleButton.isSelected()) {// 选定
			if (!IS_INDEX_TYPE.contains("xls")) {
				IS_INDEX_TYPE.add("xls");
			}
		} else {
			if (IS_INDEX_TYPE.contains("xls")) {
				IS_INDEX_TYPE.remove("xls");
			}
		}
	}

	private void cyclejComboBoxItemStateChanged(ItemEvent evt) {
		if (evt.getStateChange() == ItemEvent.SELECTED) {
			JComboBox jcb = (JComboBox) evt.getSource();
			this.IS_INDEX_CYCLE = jcb.getSelectedItem().toString();
		}
	}

	/**
	 * 初始化
	 */
	private void init() {
		IS_DIR = GlobalVar.INDEX_SCAN_DIR;
		IS_INDEX_TYPE = GlobalVar.INDEX_SCAN_TYPE;
		IS_INDEX_CYCLE = GlobalVar.INDEX_CYCLE;
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				IndexerSettingJDialog dialog = new IndexerSettingJDialog(
						new JFrame(), true);
				dialog.addWindowListener(new WindowAdapter() {

					@Override
					public void windowClosing(WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

	private JButton addjButton;
	private JButton canclejButton;
	private JComboBox cyclejComboBox;
	private JButton deductjButton;
	private JList dirjList;
	private JToggleButton docjToggleButton;
	private JLabel jLabel1;
	private JScrollPane jScrollPane1;
	private JSeparator jSeparator1;
	private JButton okjButton;
	private JToggleButton pdfjToggleButton;
	private JToggleButton txtjToggleButton;
	private JToggleButton xlsjToggleButton;
}
